package org.ezplatform.office.calendar.web.rest;

import java.io.*;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.role.RoleApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.cloud.common.util.AuthUtils;
import org.ezplatform.component.permission.service.CmpApplyScopeService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.integ.websocket.annotation.WebsocketCode;
import org.ezplatform.integ.websocket.constant.WebsocketConstant;
import org.ezplatform.integ.websocket.util.WebsocketUtils;
import org.ezplatform.office.calendar.dao.CalendarCategoryDao;
import org.ezplatform.office.calendar.dao.CalendarDao;
import org.ezplatform.office.calendar.entity.Calendar;
import org.ezplatform.office.calendar.entity.CalendarCategory;
import org.ezplatform.office.calendar.entity.CalendarDelete;
import org.ezplatform.office.calendar.entity.CalendarFinished;
import org.ezplatform.office.calendar.service.CalendarCategoryService;
import org.ezplatform.office.calendar.service.CalendarDeleteService;
import org.ezplatform.office.calendar.service.CalendarFinishedService;
import org.ezplatform.office.calendar.service.CalendarService;
import org.ezplatform.office.calendar.service.CalendarSettingService;
import org.ezplatform.office.calendar.util.CalendarExportUtil;
import org.ezplatform.office.calendar.util.CalendarSecUtils;
import org.ezplatform.office.calendar.util.CalendarSendMsgUtils;
import org.ezplatform.office.calendar.util.CalendarUtils;
import org.ezplatform.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RestController
@RequestMapping(value = "/api/w/calendar/oaCalendar")
public class CalendarWebApiController extends BaseController<Calendar, String>{

    private final static Logger LOG = LoggerFactory.getLogger(CalendarWebApiController.class);

	private final static String[] WEEKS = {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};

	@Autowired
	private CalendarCategoryDao calendarCategoryDao;

	@Autowired
    private CalendarService calendarService;

	@Autowired
	private CalendarDao calendarDao;

	@Autowired
	private CalendarFinishedService calendarFinishedService;

	@Autowired
	private PopUserScopeUtilService popUserScopeUtilService;

	@Autowired
	private CalendarCategoryService calendarCategoryService;

	@Autowired
	private UserApiService userApiService;

	@Autowired
	private CalendarDeleteService calendarDeleteService;

	@Autowired
	private CalendarSettingService calendarSettingService;

	@Autowired
	private RoleApiService roleApiService;

	@Autowired
	private LogService logService;

	@Autowired
	private CalendarExportUtil calendarExportUtil;

	@Autowired
	private CalendarSendMsgUtils calendarSendMsgUtils;

	@Autowired
	private CmpApplyScopeService cmpApplyScopeService;

    @Override
    protected BaseService<Calendar, String> getEntityService() {
        return calendarService;
    }

    /**
     * 初始化数据
     *
     * @param request
     * @param model
     * @param id
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,
            @RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }

    /**
     * 获取日程，月视图查询日程方法，包括我的日程，领导日程，下属日程，共享给我的日程
     *
     * @param request
     * @return json
     * @throws ParseException
     */
    @RequestMapping(value = "/getOaCalendar", method =RequestMethod.GET)
    @ResponseBody
    public OperationResult getOaCalendar(HttpServletRequest request) throws ParseException {
    	WebUser user = WebUtils.getCurrentUser();
    	String viewType = StringUtils.null2String(request.getParameter("viewType"));
    	String sharedId = "";
    	//如果是共享日程，sharedId是共享给我的人的ID
    	if("share".equals(viewType)){
    		sharedId = StringUtils.null2String(request.getParameter("sharedId"));
			//安全校验
			if(!ValidateUtils.validateSql(sharedId)){
				throw new ValidationException("非法参数");
			}
    	}
    	String title = StringUtils.null2String(request.getParameter("title"));
		try {
			title = title .replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			title = title .replaceAll("\\+", "%2B");
			title = java.net.URLDecoder.decode(title, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}

    	String category = StringUtils.null2String(request.getParameter("category"));
    	String start = request.getParameter("start");
    	String end = request.getParameter("end");
		String leader = request.getParameter("leader");
		String ingOrFinish = request.getParameter("ingOrFinish");
		String isLeader = request.getParameter("isLeader");
		String selectViewType = request.getParameter("selectViewType");
		String suffix = request.getParameter("_");

		//安全校验
		if(!ValidateUtils.validateSql(suffix) || !ValidateUtils.validateComm(suffix)){
			throw new ValidationException("非法参数");
		}


//		if(StringUtils.isBlank(start)){
//			start = CalendarUtils.getMonthDateBegin();
//		}
//
//		if(StringUtils.isBlank(end)){
//			end = CalendarUtils.getMonthDateEnd();
//		}

		//安全校验
		if(!ValidateUtils.validateSql(title) || title.length()>20){
			throw new ValidationException("非法参数");
		}

		//安全校验
		if(!ValidateUtils.validateSql(category) || !ValidateUtils.validateComm(category)){
			throw new ValidationException("非法参数");
		}
		//安全校验
		if(!ValidateUtils.validateSql(start)){
			throw new ValidationException("非法参数");
		}
		//安全校验
		if(!ValidateUtils.validateSql(end) || !ValidateUtils.validateComm(end)){
			throw new ValidationException("非法参数");
		}
		//安全校验
		if(!ValidateUtils.validateSql(leader)  || !ValidateUtils.validateComm(leader)){
			throw new ValidationException("非法参数");
		}
		//安全校验
		if(!ValidateUtils.validateSql(ingOrFinish)){
			throw new ValidationException("非法参数");
		}
		//安全校验
		if(!ValidateUtils.validateSql(isLeader)) {
			throw new ValidationException("非法参数");
		}
		//安全校验
		if(!ValidateUtils.validateSql(selectViewType) || !ValidateUtils.validateComm(selectViewType)) {
			throw new ValidationException("非法参数");
		}
		//查询系统管理工作日历中设置的节假日
		List<Map> workHolidayList = this.calendarSettingService.getAllHoliWorkDay(start,end);
		Map<String,Object> map = new HashMap<>();
		map.put("workHolidayList", workHolidayList);

		//如果是领导日程complateCalendar
		if (StringUtils.isNotBlank(leader)) {
			if("1".equals(isLeader)){
				String result = this.calendarService.getOaCalendarForLeader("", sharedId, user.getCorpId(), title, category,"calendar", start, end, TOKEN,leader,user);
				//领导日程，对参与人进行处理
				JSONArray ja = JSONArray.parseArray(result);
				List<Map<String,String>> resultList = JSONArray.toJavaObject(ja,List.class);
				resultList = calendarService.changePartToLeaderName(resultList, sharedId, user.getCorpId(), user.getJwtToken(),selectViewType);

				map.put("result", JSONArray.toJSONString(resultList));
				return OperationResult.buildSuccessResult(map);
			}else{
				String result = this.calendarService.getOaCalendar("", sharedId, user.getCorpId(), title, category,"calendar", start, end, TOKEN,leader,user);
				if("customCalendar".equals(selectViewType)){
					JSONArray ja = JSONArray.parseArray(result);
					List<Map<String,String>> resultList = JSONArray.toJavaObject(ja,List.class);
					resultList = calendarService.changePartToLeaderName(resultList, sharedId, user.getCorpId(), user.getJwtToken(),selectViewType);
					map.put("result", JSONArray.toJSONString(resultList));
				}else{

					map.put("result", result.replace("flexbracketB","[").replace("flexbracketE","]"));
				}

				return OperationResult.buildSuccessResult(map);
			}
		}
		String result = "";
		//选择进行中或者已完成
		if(StringUtils.isNotEmpty(ingOrFinish)) {
			 result = this.calendarService.getOaCalendar(sharedId, user.getUserId(), user.getCorpId(), title, category,viewType, start, end, TOKEN,leader,ingOrFinish);
		}else {
			 result = this.calendarService.getOaCalendar(sharedId, user.getUserId(), user.getCorpId(), title, category,viewType, start, end, TOKEN,leader,user);
		}
    	map.put("result", result.replace("flexbracketB","[").replace("flexbracketE","]"));
    	return OperationResult.buildSuccessResult(map);
    }

    /**
     * 获取日程自定义周视图数据(我的日程/领导日程)
     * @param request
     * @return
     */
    @RequestMapping(value = "/getOaWeekCalendar", method = RequestMethod.GET)
    @ResponseBody
    public Page getOaWeekCalendar(HttpServletRequest request){
    	WebUser user = WebUtils.getCurrentUser();
    	String userId = user.getUserId();
    	String corpId = user.getCorpId();
    	String token = user.getJwtToken();
    	String viewType = StringUtils.null2String(request.getParameter("viewType"));
    	String suffix = StringUtils.null2String(request.getParameter("_"));

		if(!ValidateUtils.validateSql(suffix) || !ValidateUtils.validateComm(suffix)){
			throw new ValidationException("非法参数");
		}

		if(!ValidateUtils.validateSql(viewType) || !ValidateUtils.validateComm(viewType)){
			throw new ValidationException("非法参数");
		}


    	String sharedId = "";
    	if("share".equals(viewType)){
    		sharedId = StringUtils.null2String(request.getParameter("sharedId"));
			if(!ValidateUtils.validateSql(sharedId)){
				throw new ValidationException("非法参数");
			}
    	}
    	String title = StringUtils.null2String(request.getParameter("title"));
		try {
			title = title .replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			title = title .replaceAll("\\+", "%2B");
			title = java.net.URLDecoder.decode(title, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}

		if(!ValidateUtils.validateSql(title)){
			throw new ValidationException("非法参数");
		}
    	String category = StringUtils.null2String(request.getParameter("category"));
		if(!ValidateUtils.validateSql(category) || !ValidateUtils.validateComm(category)){
			throw new ValidationException("非法参数");
		}
    	String start = request.getParameter("startDate");
//		if(StringUtils.isBlank(start)){
//			start = DateUtils.formatDate(CalendarUtils.getBeginDayOfWeek(),"yyyy-MM-dd");
//		}
		if(!ValidateUtils.validateSql(start)){
			throw new ValidationException("非法参数");
		}
    	String end = request.getParameter("end");
//		if(StringUtils.isBlank(end)){
//			end = DateUtils.formatDate(CalendarUtils.getEndDayOfWeek(),"yyyy-MM-dd");
//		}
		if(!ValidateUtils.validateSql(end)){
			throw new ValidationException("非法参数");
		}
    	String ingOrFinish = StringUtils.null2String(request.getParameter("ingOrFinish"));
		if(!ValidateUtils.validateSql(ingOrFinish)){
			throw new ValidationException("非法参数");
		}
		//日程设置里领导日程周视图排序种类，1：按时间排序，0：按领导排序
    	String custWeekType = StringUtils.null2String(request.getParameter("custWeekType"));
		if(!ValidateUtils.validateSql(custWeekType) || !ValidateUtils.validateComm(custWeekType)){
			throw new ValidationException("非法参数");
		}
		if(StringUtils.isNotEmpty(end)) {
			end = CalendarUtils.addDays(end,-1,"yyyy-MM-dd");
    	}

		if (StringUtils.isBlank(start) || StringUtils.isBlank(end)) {
			return null;
		}
    	String leader = request.getParameter("leader");
		if(!ValidateUtils.validateSql(leader)){
			throw new ValidationException("非法参数");
		}

		//选中的视图
		String selectViewType = request.getParameter("selectViewType");
		if(!ValidateUtils.validateSql(selectViewType) || !ValidateUtils.validateComm(selectViewType)){
			throw new ValidationException("非法参数");
		}

    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);


		return  this.calendarService.getOaWeekCalendarResult(leader,pageable,category,sharedId,corpId,title,start,end,token,userId,custWeekType,viewType,ingOrFinish,selectViewType);

    }

	/**
	 * 获取日程自定义日视图数据(我的日程/领导日程/下属日程/共享日程)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getOaDayCalendar", method = RequestMethod.GET)
	@ResponseBody
	public Page getOaDayCalendar(HttpServletRequest request) throws ParseException {
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		String token = user.getJwtToken();
		String viewType = StringUtils.null2String(request.getParameter("viewType"));
		String sharedId = "";
		String shareId = "";
		//如果是共享日程，sharedId是共享给我的人的ID
		if("share".equals(viewType)){
			sharedId = StringUtils.null2String(request.getParameter("sharedId"));
			shareId = StringUtils.null2String(request.getParameter("shareId"));
		}
		String title = StringUtils.null2String(request.getParameter("title"));

		try {
			title = title .replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			title = title .replaceAll("\\+", "%2B");
			title = java.net.URLDecoder.decode(title, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}

		String category = StringUtils.null2String(request.getParameter("category"));
		String start = request.getParameter("startDate");
		String end = request.getParameter("end");
		String leader = request.getParameter("leader");
		String ingOrFinish = request.getParameter("ingOrFinish");
		// 标记是否是我的日程视图
		String myCalendar = request.getParameter("myCalendar");
		// 上午/下午模式是否开启
		String leaderTimeSettingType = request.getParameter("leaderTimeSettingType");

		String suffix = request.getParameter("_");

		if(!ValidateUtils.validateSql(suffix) || !ValidateUtils.validateComm(suffix)){
			throw new ValidationException("非法参数");
		}

		if(!ValidateUtils.validateSql(start) || !ValidateUtils.validateComm(start)){
			throw new ValidationException("非法参数");
		}

		String order = request.getParameter("order");
		if(!ValidateUtils.validateComm(order)){
			throw new ValidationException("非法参数");
		}

//		if(StringUtils.isBlank(start)){
//			start = DateUtils.formatDate(new Date(),"yyyy-MM-dd");
//		}
//
//		if(StringUtils.isBlank(end)){
//			end = DateUtils.formatDate(new Date(),"yyyy-MM-dd");
//		}

		//查询系统管理工作日历中设置的节假日
		//List<Map> workHolidayList = this.calendarSettingService.getAllHoliWorkDay(start,end);
		String selectViewType = request.getParameter("selectViewType");//选择的标签  leaderCalendar 领导日程 subCalendar 下属日程  shareCalendar 共享日程 myCalendar 我的日程


		return this.calendarService.getOaDayCalendarResult(leader,sharedId,corpId,title,category,start,end,token,selectViewType,leaderTimeSettingType,userId,viewType,ingOrFinish,myCalendar,shareId,user);
	}

    /**
     * 获取领导数据(只有查看领导日程才有领导数据)
     * @param request
     * @return
     */
    @RequestMapping(value = "/getOaOwnerInfo", method = RequestMethod.GET)
    @ResponseBody
    public Page getOaLeaderInfo(HttpServletRequest request) throws ParseException {
        WebUser user = WebUtils.getCurrentUser();
        String userId = user.getUserId();//登录人id
        String corpId = user.getCorpId();//单位Id
        String token = user.getJwtToken();//身份信息
        String viewType = StringUtils.null2String(request.getParameter("viewType"));//查看类型 默认值    calendar    点击领导日程 share 点击下属日程、共享日程 share  点击我的日程  calndar
        String sharedId = "";
        //如果是共享日程，sharedId是共享给我的人的ID
        if("share".equals(viewType)){
            sharedId = StringUtils.null2String(request.getParameter("sharedId"));
        }
        String title = StringUtils.null2String(request.getParameter("title"));//搜索内容
		try {
			title = title .replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			title = title .replaceAll("\\+", "%2B");
			title = java.net.URLDecoder.decode(title, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
        String category = StringUtils.null2String(request.getParameter("category"));//日程分类
        String start = request.getParameter("start");//搜索开始时间
        String end = request.getParameter("end");//搜索结束时间
        String leader = request.getParameter("leader");//领导日程 1
		String ingOrFinish = request.getParameter("ingOrFinish");//选中了进行中还是已完成

        //2022-01-21  新增判断选项，判断是哪个视图
        String selectViewType = request.getParameter("selectViewType");//选择的哪个日程  我的  myCalendar  领导 leaderCalendar 下属 	subCalendar  共享 shareCalendar

		List<Map<String,Object>> mapResult = this.calendarService.getOaOwnerInfoResult(sharedId,corpId,title,category,start,end,token,leader,selectViewType, viewType,userId,ingOrFinish,user);

		return new PageImpl(mapResult);
    }

    /**
     * 获取日程列表，列表视图查询方法
     *
     * @param request
     * @return json
     */
    @RequestMapping(value = "/getOaCalendarList", method = RequestMethod.GET)
    @ResponseBody
    public Page getOaCalendarList(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String userId = user.getUserId();//登录人id
        String corpId = user.getCorpId();//单位id
        String token = user.getJwtToken();// 身份信息
        String viewType = StringUtils.null2String(request.getParameter("viewType"));//查看类型
        String sharedId = "";
        if ("share".equals(viewType)) {
            sharedId = StringUtils.null2String(request.getParameter("sharedId"));//共享人id
        }
        String title = StringUtils.null2String(request.getParameter("title"));//搜索内容
		try {
			title = title .replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			title = title .replaceAll("\\+", "%2B");
			title = java.net.URLDecoder.decode(title, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		String category = StringUtils.null2String(request.getParameter("category"));//日程分类
        String start = request.getParameter("startDate");//搜索开始时间
		String start_unuse = request.getParameter("start");
        String end = request.getParameter("end");//搜索结束时间
		String suffix = request.getParameter("_");

		if(!ValidateUtils.validateSql(suffix) || !ValidateUtils.validateComm(suffix)){
			throw new ValidationException("非法参数");
		}

		if(!ValidateUtils.validateSql(start) || !ValidateUtils.validateComm(start)){
			throw new ValidationException("非法参数");
		}

		if(!ValidateUtils.validateSql(start_unuse) || !ValidateUtils.validateComm(start_unuse)){
			throw new ValidationException("非法参数");
		}

		if(!ValidateUtils.validateSql(end) || !ValidateUtils.validateComm(end)){
			throw new ValidationException("非法参数");
		}

		if(!ValidateUtils.validateSql(viewType) || !ValidateUtils.validateComm(viewType)){
			throw new ValidationException("非法参数");
		}

		if(!ValidateUtils.validateSql(title)){
			throw new ValidationException("非法参数");
		}


//		if(StringUtils.isBlank(start)){
//			start = CalendarUtils.getMonthDateBegin();
//		}
//
//		if(StringUtils.isBlank(end)){
//			end = CalendarUtils.getMonthDateEnd();
//		}

        String ingOrFinish = StringUtils.null2String(request.getParameter("ingOrFinish"));//选择了进行中或者已完成
        if (StringUtils.isBlank(start) || StringUtils.isBlank(end)) {
            return null;
        }
        String leader = request.getParameter("leader");// 领导日程 1
		if(!ValidateUtils.validateSql(leader) || !ValidateUtils.validateComm(leader)){
			throw new ValidationException("非法参数");
		}
        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);//分页参数
		List<Map<String, String>> finalResult = this.calendarService.getOaCalendarListResult(start, end, leader, pageable, category, sharedId, corpId, title, token, userId, viewType,ingOrFinish);
        Map<String, String> extMap = new HashMap<>();
        extMap.put("userId",userId);
    	return new PageImpl(CalendarSecUtils.calendarEncodeListByIdUserIdString(finalResult,extMap));
    }

    /**
     * 判断是否有日程设置权限
     * @param request
     * @return
     */
    @RequestMapping(value = "/ifSetting", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult ifSetting(HttpServletRequest request){
    	Map map = new HashMap();
    	String user = StringUtils.null2String(WebUtils.getCurrentUser().getRoleCodes());
    	map.put("ifSetting", false);
    	if(StringUtils.isNotEmpty(user)) {
    		map.put("ifSetting", user.contains("appAdminRole"));
    	}
    	return OperationResult.buildSuccessResult(map);
    }

    /**
     * 查看日程
     *
     * @param request
     * @return json
     * @throws ParseException
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult viewCalendarInfo(HttpServletRequest request) throws ParseException {
    	Map<String, Object> map;
    	WebUser user = WebUtils.getCurrentUser();
    	String userId = user.getUserId();// 登录人id
    	String corpId = user.getCorpId();// 单位id
    	String token = user.getJwtToken();// 身份信息
    	int userLevel = user.getSecretLevel();//用户密级
    	String logLeader = StringUtils.null2String(request.getParameter("logLeader"));// 日志标识
    	String weekLeader = StringUtils.null2String(request.getParameter("weekLeader"));//领导日志类型
    	String leaderCateId = StringUtils.null2String(request.getParameter("leaderCateId"));//领导日程分类
        String selectViewType = StringUtils.null2String(request.getParameter("selectViewType"));//选择的哪个日程  我的  myCalendar  领导 leaderCalendar 下属 	subCalendar  共享 shareCalendar  其他日程 customCalendar
		String secdatacode = StringUtils.null2String(request.getParameter("secdatacode"));//加密信息
        Map<String, String> paramMap = new HashMap<String, String>();
    	String viewType = request.getParameter("viewType");//查看类型 -1会议 0 其他
    	String id = request.getParameter("id");//日程id
        String type = request.getParameter("type");//查看类型  view 查看 其他编辑
        String start = request.getParameter("start");//日程开始时间
        String end = request.getParameter("end");//日程结束时间
        String repeat = request.getParameter("repeat");// 1 重复日程
        //相关领导id
        String leaderId = request.getParameter("leaderId");

		String suffix = request.getParameter("_");

        //校验id
		if (!ValidateUtils.validateId(id)) {
			throw new ValidationException("非法参数");
		}

		if (!ValidateUtils.validateId(viewType) || !ValidateUtils.validateComm(viewType)) {
			throw new ValidationException("非法参数");
		}

		if (!ValidateUtils.validateSql(secdatacode) || !ValidateUtils.validateComm(secdatacode)) {
			throw new ValidationException("非法参数");
		}

		if (!ValidateUtils.validateId(suffix) || !ValidateUtils.validateComm(suffix)) {
			throw new ValidationException("非法参数");
		}


		Calendar calendar = this.calendarService.findOne(id);
		if(calendar!=null && calendar.getId()!=null){
            //平行越权校验
            Map<String,String> extMap = new HashMap<>();
            extMap.put("userId",userId);
            if(!CalendarSecUtils.calendarCheckDataByIdUserId(calendar.getId(),secdatacode,extMap)){
                return OperationResult.buildFailureResult("操作失败，参数有误");
            }
		}

        map = this.calendarService.viewCalendarInfo(viewType,corpId,id,token,userId,type,logLeader,weekLeader,leaderCateId,repeat,start,end,userLevel,selectViewType,leaderId);


    	return OperationResult.buildSuccessResult(map);
    }


    /**
     * 共享日程查看
     *
     * @param request
     * @return json
     */
    @RequestMapping(value = "/getShareInfo", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getShareInfo(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<>();
    	String id = request.getParameter("id");
    	Calendar calendar = this.calendarService.findOne(id);
    	if(calendar == null){
			return null;
		}
		logService.saveModuleLog("calendar:mycalendar:03", calendar.getTitle(), "");
    	map.put("entity", calendar);
    	String participant = popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "participant", calendar.getParticipant());
		String viewer = popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "viewer", calendar.getViewer());
		String maintainer = popUserScopeUtilService.getScopeTypeValue("oa_calendar_scope", "oa_calendar", "maintainer", calendar.getMaintainer());
		Map<String, String> scope = new HashMap<>();
		scope.put("participant", participant);
		scope.put("viewer", viewer);
		scope.put("maintainer", maintainer);
		map.put("scope", scope);
    	return OperationResult.buildSuccessResult(map);
    }

    /**
     * 共享日程
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/shareCalendar", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult shareCalendar(HttpServletRequest request) {
    	String id = request.getParameter("id");
    	Calendar calendar = this.calendarService.findOne(id);
        //共享参与日程
        String jsonView = StringUtils.null2String(request.getParameter("jsonStrViewer"));
    	String jsonMaintain = StringUtils.null2String(request.getParameter("jsonStrMaintainer"));

    	String viewer = StringUtils.null2String(calendar.getViewer());
    	if("".equals(viewer)){
    		viewer = UuidUtils.UUID();
    		calendar.setViewer(viewer);
    	}
    	this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, jsonView, "oa_calendar", "viewer");

    	String maintainer = StringUtils.null2String(calendar.getMaintainer());
    	if("".equals(maintainer)){
    		maintainer = UuidUtils.UUID();
    		calendar.setMaintainer(maintainer);
    	}
    	this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, jsonMaintain, "oa_calendar", "maintainer");
    	logService.saveModuleLog("calendar:mycalendar:02", calendar.getTitle(), "");
    	return super.editSave(calendar);
    }

    /**
     * 获取单个日程事件json
     *
     * @param request
     * @return json
     */
    @RequestMapping(value = "/getEventData", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getEventData(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();//单位id
    	String userId = user.getUserId();//登录人Id
    	String token = user.getJwtToken();//身份信息
    	String id = request.getParameter("id");//日程id
        String viewType = request.getParameter("viewType");//查看类型 默认值    calendar    点击领导日程 share 点击下属日程、共享日程 share  点击我的日程  calndar
        String searchStart = StringUtils.null2String(request.getParameter("start"));//开始时间
        String searchEnd = StringUtils.null2String(request.getParameter("end"));//结束时间

        String resultJsonStr = this.calendarService.getEventDataResult(id,viewType,userId,corpId,token,searchStart,searchEnd);

    	return OperationResult.buildSuccessResult(resultJsonStr);
    }

    /**
     *
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/getEventDates", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getEventDates(HttpServletRequest request) throws ParseException {
    	WebUser user = WebUtils.getCurrentUser();
    	String viewType = StringUtils.null2String(request.getParameter("viewType")); // 查看类型

    	String yearMonth = StringUtils.null2String(request.getParameter("yearMonth"));
    	String prevDays = StringUtils.null2String(request.getParameter("prevDays"));
    	String[] ym = yearMonth.split("-");
    	String start = CalendarUtils.getFirstDayOfMonth(Integer.parseInt(ym[0]), Integer.parseInt(ym[1]));
    	start = CalendarUtils.addDays(start, -Integer.parseInt(prevDays), "yyyy-MM-dd");
    	String end = CalendarUtils.getLastDayOfMonth(Integer.parseInt(ym[0]), Integer.parseInt(ym[1]));

    	String sharedId = "";
    	if("share".equals(viewType)){
    		sharedId = request.getParameter("sharedId");
    	}

    	List<Map<String, String>> list = this.calendarService.getOaCalendarDate(sharedId, user.getUserId(), user.getCorpId(), viewType, start, end, TOKEN,"2");

    	return OperationResult.buildSuccessResult(list);
    }

    /**
     * 当前日程是否完成，月视图完成/取消完成日程方法
     * @param request
     */
    @RequestMapping(value = "/complateCalendar", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult complateCalendar(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String calendarId = request.getParameter("calendarId");
        String isComplate = request.getParameter("isComplate");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String finishUserId = request.getParameter("finishUserId");
        String updateComplate = request.getParameter("updateComplate");
        String userId = user.getUserId();
        //完成日程类型 我的  myCalendar  领导 leaderCalendar  共享 shareCalendar
        String finishType = request.getParameter("finishType");

        //数据校验
		if(!ValidateUtils.validateId(calendarId)){
			throw new ValidationException("非法参数");
		}

        //领导和共享日程下，完成人id页面为准
        if("shareCalendar".equals(finishType) || "leaderCalendar".equals(finishType)){
            userId = finishUserId;
        }

        if("1".equals(isComplate)) {
            isComplate = "0";
        }else {
            isComplate = "1";
        }

        return calendarService.complateCalendar(isComplate,calendarId,startDate,endDate,userId,updateComplate,finishType);
    }


    /**
     * 保存/修改日程
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSave", method = RequestMethod.POST)
    @ResponseBody
	public OperationResult editSave(@ModelAttribute("entity") Calendar entity, HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String userId = user.getUserId();
    	String corpId = user.getCorpId();
    	String token = user.getJwtToken();
    	String leaderUserIds = StringUtils.null2String(request.getParameter("leaderUserId"));
    	String belongTo = StringUtils.null2String(request.getParameter("belongTo"));
    	String weekSelectValue = StringUtils.null2String(request.getParameter("weekSelectValue"));
    	String monthSelectValue = StringUtils.null2String(request.getParameter("monthSelectValue"));
    	String monthRadioValue = StringUtils.null2String(request.getParameter("monthRadioValue"));
    	String isShared = StringUtils.null2String(request.getParameter("isShared"));// 1 共享日程 其他 我的日程
    	// 是否设置上午/下午
		String leaderTimeSettingType = StringUtils.null2String(request.getParameter("leaderTimeSettingType"));


		String duplicateTypeTwo = StringUtils.null2String(request.getParameter("duplicateTypeTwo"));
		//安全校验
		if(!ValidateUtils.validateSql(duplicateTypeTwo) || !ValidateUtils.validateComm(duplicateTypeTwo)){
			throw new ValidationException("非法参数");
		}

    	Map<String,String> cate = new HashMap<>();
    	//获取新的分类id
    	String newCalendarCateId = UuidUtils.UUID();
    	String oldCalendarCateId = entity.getCalendarCategory();

    	//参数校验
		this.calendarService.verifySaveCalendar(request);

    	//平行越权校验
		if(StringUtils.isNotBlank(entity.getId())){
			Calendar calendarCheck = this.calendarService.findOne(entity.getId());
			if(calendarCheck!=null && calendarCheck.getId()!=null){
                //平行越权校验
                Map<String,String> extMap = new HashMap<>();
                extMap.put("userId",userId);
                if(!CalendarSecUtils.calendarCheckDataByIdUserId(calendarCheck.getId(),entity.getSecdatacode(),extMap)){
                    return OperationResult.buildFailureResult("操作失败，参数有误");
                }
			}
		}

		//校验分类id
		if (!ValidateUtils.validateId(entity.getCalendarCategory())) {
			throw new ValidationException("非法参数");
		}

    	boolean isChangeCateId = false;
    	boolean leaderUserNumberFlag = false;
    	//如果是领导日程新建
    	if(StringUtils.isNotEmpty(leaderUserIds)) {
    		List<String> leaderUserList = Arrays.asList(leaderUserIds.split(","));
    		if(leaderUserList.size() == 1) {
    			leaderUserNumberFlag = true;
    			//保存前 处理下系统初始化的工作日程分类(calendarSysWork)
            	CalendarCategory calendarSysCategory = calendarCategoryDao.getCategoryById(entity.getCalendarCategory(),user.getCorpId());
            	String cateOwer = leaderUserList.get(0);
            	//如果是工作系统日程
            	if(StringUtils.equals("calendarSysWork", calendarSysCategory.getCode())) {
            		//需要重新设置id,createdBy,code
            		CalendarCategory ca = new CalendarCategory();
            		ca.setId(newCalendarCateId);
            		ca.setCreatedBy(cateOwer);
            		ca.setCode("singleWork");
            		ca.setBackColor(calendarSysCategory.getBackColor());
            		ca.setCategory(calendarSysCategory.getCategory());
            		ca.setCorpId(calendarSysCategory.getCorpId());
            		ca.setCreator(calendarSysCategory.getCreator());
            		ca.setMaintainer(calendarSysCategory.getMaintainer());
            		ca.setName(calendarSysCategory.getName());
            		ca.setSortNo(calendarSysCategory.getSortNo());
            		ca.setSource(calendarSysCategory.getSource());
            		ca.setViewer(calendarSysCategory.getViewer());
            		entity.setCalendarCategory(ca.getId());
            		//保存类别
            		this.calendarCategoryService.save(ca);
            		isChangeCateId = true;
            	}
    		}else {
    			List<Map> cateList = this.calendarService.getAllLeaderWorkCate(leaderUserList);
        		Map<String,String> newWorkCate = new HashMap<String,String>();
        		if(CollectionUtils.isNotEmpty(cateList)) {//有个人的工作日程,获取所有领导的工作日程map
        			for(Map map : cateList) {
        				cate.put(StringUtils.null2String(map.get("createdBy")), StringUtils.null2String(map.get("id")));
        			}
        			Set<String> set = cate.keySet();
        			for(String leaderId : leaderUserList) {
        				if(!set.contains(leaderId)) {
        					String cateId = UuidUtils.UUID();
        					cate.put(leaderId,cateId);
        					newWorkCate.put(leaderId,cateId);
        				}
        			}
        		}else {//全为初始化工作日程
        			for(String leaderId : leaderUserList) {
        				String cateId = UuidUtils.UUID();
        				cate.put(leaderId,cateId);
        				newWorkCate.put(leaderId,cateId);
        			}
        		}
        		//批量新建个人 工作日程
        		if(MapUtils.isNotEmpty(newWorkCate)) {
        			List<CalendarCategory> list = new ArrayList<>();
        			for(Map.Entry<String, String> entry : newWorkCate.entrySet()) {
        				CalendarCategory ca = new CalendarCategory();
                		ca.setId(entry.getValue());
                		ca.setCreatedBy(entry.getKey());
                		ca.setCode("singleWork");
                		ca.setBackColor("#548dd4");
                		ca.setCategory("calendarOwner");
                		ca.setCorpId(corpId);
                		ca.setCreator("");
                		ca.setMaintainer("");
                		ca.setName("工作日程");
                		ca.setSortNo(0);
                		ca.setSource("");
                		ca.setViewer("");
                		list.add(ca);
        			}
        			this.calendarCategoryService.save(list);
        		}
    		}
    	}else {
    		//保存前 处理下系统初始化的两个日程分类(calendarSysWork,calendarSysPerson)
        	CalendarCategory calendarSysCategory = calendarCategoryDao.getCategoryById(entity.getCalendarCategory(),user.getCorpId());

        	//日程分类初始化
        	String cateOwer = "";
    		if("1".equals(isShared)){
    		    cateOwer = request.getParameter("belongTo");
    		}else{
    			cateOwer = user.getUserId();
    		}
    		if(StringUtils.equals("calendarSysWork", calendarSysCategory.getCode()) || StringUtils.equals("calendarSysPerson", calendarSysCategory.getCode())) {
				//需要重新设置id,createdBy,code
				CalendarCategory ca = new CalendarCategory();
				ca.setId(newCalendarCateId);
				ca.setCreatedBy(cateOwer);
				//如果是工作系统日程
	        	if(StringUtils.equals("calendarSysWork", calendarSysCategory.getCode())) {
	        		ca.setCode("singleWork");
	        	}
	        	//如果是个人系统日程
	        	if(StringUtils.equals("calendarSysPerson", calendarSysCategory.getCode())) {
	        		ca.setCode("singlePerson");
	        	}
	        	ca.setBackColor(calendarSysCategory.getBackColor());
	        	ca.setCategory(calendarSysCategory.getCategory());
	        	ca.setCorpId(calendarSysCategory.getCorpId());
	        	ca.setCreator(calendarSysCategory.getCreator());
	        	ca.setMaintainer(calendarSysCategory.getMaintainer());
	        	ca.setName(calendarSysCategory.getName());
	        	ca.setSortNo(calendarSysCategory.getSortNo());
	        	ca.setSource(calendarSysCategory.getSource());
	        	ca.setViewer(calendarSysCategory.getViewer());
	        	entity.setCalendarCategory(ca.getId());
	        	//保存类别
	        	this.calendarCategoryService.save(ca);
	        	isChangeCateId = true;
    		}
    	}


    	Date startNow = new Date();
		Date endNow = new Date();
		if(StringUtils.isNotBlank(entity.getExpiryReminder())){
			if(ValidateUtils.validateId(entity.getExpiryReminder()) == false){
				throw new ValidationException("非法参数");
			}
			if(!ValidateUtils.validateChar(entity.getExpiryReminder(), "%+") ){
				throw new ValidationException("非法参数");
			}
		}
		//转换是否推送开关
		if(entity.getExpiryReminder() == null || StringUtils.equals(entity.getExpiryReminder(), "0")) {
			entity.setExpiryReminder("no");
			entity.setRemindStyle("");
		}else {
			entity.setExpiryReminder("yes");
		}
    	String startTime = StringUtils.null2String(request.getParameter("startTimeStr"));
        String endTime = StringUtils.null2String(request.getParameter("endTimeStr"));
        // 上午/下午标记 0下午、1上午
        String setTimeFlag = StringUtils.null2String(request.getParameter("setTimeFlag"));
        String allDay = StringUtils.null2String(entity.getIsAllDay());
        if(StringUtils.equals("week", StringUtils.null2String(entity.getDuplicateType()))) {
        	entity.setWeekMonthDuplicateType(weekSelectValue);
        }
        if(StringUtils.equals("month", StringUtils.null2String(entity.getDuplicateType()))) {
        	entity.setWeekMonthDuplicateType(monthSelectValue+monthRadioValue);
        }
        if("1".equals(allDay)){
        	Date date = new Date();
        	try {
        		date = CalendarUtils.getDataByStr(StringUtils.null2String(request.getParameter("startDate")), "yyyy-MM-dd");
			} catch (Exception e) {
				LOG.error("时间转换失败",e);
			}
        	entity.setStartDate(date);
        	entity.setEndDate(null);
        	// 上午/下午为空
			entity.setSetTimeFlag(null);
			// 非全天日程并且选择上午/下午模式
        }else if (!"1".equals(allDay) && StringUtils.isNotBlank(leaderTimeSettingType)) {
        	// 选择上午/下午
			Date date = new Date();
			try {
				date = CalendarUtils.getDataByStr(StringUtils.null2String(request.getParameter("startDate")), "yyyy-MM-dd");
			} catch (Exception e) {
				LOG.error("时间转换失败",e);
			}
			entity.setStartDate(date);
			//2022-01-04 修改，上午下午模式下新增默认值
			entity.setEndDate(date);
			entity.setStartTime(CalendarUtils.getSeconds(startTime));
			entity.setEndTime(CalendarUtils.getSeconds(endTime));
        }else {
			entity.setStartTime(CalendarUtils.getSeconds(startTime));
			entity.setEndTime(CalendarUtils.getSeconds(endTime));
			entity.setIsAllDay("0");
			entity.setSetTimeFlag(null);
		}

        String id = StringUtils.null2String(entity.getId());
        String type = StringUtils.null2String(request.getParameter("updateType"));//"current"-编辑当前日程，"all"-编辑全部日程
        if("".equals(id)){
        	entity.setIsMain("1");
    		entity.setCorpId(user.getCorpId());

    		if("1".equals(isShared)){
    			entity.setCalendarOwner(belongTo);
    		}else{
    			entity.setCalendarOwner(user.getUserId());
    		}
    	}else{//日程编辑
        	if(!"".equals(id)){
    			if("current".equals(type)){
    				entity.setId(id);
    			}else {
    				Calendar calendar = this.calendarService.findOne(id);
    				startNow = calendar.getStartDate();
    				endNow = calendar.getEndDate();
    			}
    		}
    		if(!"no".equals(entity.getDuplicateType())){//重复日程
    			String isMain = entity.getIsMain();
    			if("".equals(type)){//主日程
    				this.calendarService.deleteByBelong(id);
        		}else{//重复日程
        			if("1".equals(isMain)&& "current".equals(type)){//未修改过的重复日程
        				String updateStartDate = request.getParameter("updateStartDate");
            			String updateEndDate = request.getParameter("updateEndDate");
            			try {
        					entity.setStartDate(CalendarUtils.getDataByStr(updateStartDate, "yyyy-MM-dd"));
        					entity.setEndDate(CalendarUtils.getDataByStr(updateEndDate, "yyyy-MM-dd"));
        				} catch (Exception e) {
        					LOG.error("时间转化失败",e);
        				}
            			entity.setId(null);
            			entity.setIsMain("0");
            			entity.setBelongCalendar(id);
        			}
        			if("all".equals(type)){
        				entity.setStartDate(startNow);
        				entity.setEndDate(endNow);
        				this.calendarService.updateMainCalendar(entity);
        				String calendarId = id;
        				if("0".equals(isMain)){//已修改过的重复日程
        					calendarId = entity.getBelongCalendar();
        				}
        				this.calendarService.deleteByBelong(calendarId);
        			}
        		}
    		}else {
    			entity.setDuplicateEndType(null);
    		}
    		//将当前登录人不可查看的附件与编辑后的附件组成完整的附件id再保存
    		String noEditAttachment = StringUtils.null2String(request.getParameter("noEditAttachment"));
    		String attr = StringUtils.null2String(entity.getAttachment());
    		entity.setAttachment(noEditAttachment+attr);
    	}

        if(entity.getDuplicateType() == null){
        	entity.setDuplicateType("no");
        }
        if(entity.getDuplicateEndType() == null){
        	entity.setDuplicateEndType("always");
        }
        if(entity.getExpiryReminder() == null){
        	entity.setExpiryReminder("no");
        }

        //共享参与日程
        String jsonPart = StringUtils.null2String(request.getParameter("jsonStrPart"));
        String jsonView = StringUtils.null2String(request.getParameter("jsonStrViewer"));
    	String jsonMaintain = StringUtils.null2String(request.getParameter("jsonStrMaintainer"));

    	String oldCalendarTitle = "";
    	if(StringUtils.isNotEmpty(id)) {
    		Calendar oldCalendar = this.calendarService.findOne(id);
    		if(oldCalendar != null && oldCalendar.getTitle() != null) {
    			oldCalendarTitle = oldCalendar.getTitle();
    		}
    	}

    	OperationResult operationResult = new OperationResult();
        if(StringUtils.isNotEmpty(leaderUserIds)) {//领导日程新建
        	List<Calendar> list = new ArrayList<>();
        	if(leaderUserNumberFlag) {
        		String partId = UuidUtils.UUID();
        		String canViewId = UuidUtils.UUID();
        		String maintainId = UuidUtils.UUID();
        		Calendar c = new Calendar();
        		BeanUtils.copyProperties(entity,c);
        		c.setCalendarOwner(leaderUserIds);
        		c.setParticipant(partId);
        		c.setViewer(canViewId);
        		c.setMaintainer(maintainId);
        		list.add(c);
        		this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", partId, jsonPart, "oa_calendar", "participant");
        		this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", canViewId, jsonView, "oa_calendar", "viewer");
        		this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainId, jsonMaintain, "oa_calendar", "maintainer");
        	}else {
        		for(String leaderId : Arrays.asList(leaderUserIds.split(","))) {
        			String partId = UuidUtils.UUID();
            		String canViewId = UuidUtils.UUID();
            		String maintainId = UuidUtils.UUID();
            		Calendar c = new Calendar();
            		BeanUtils.copyProperties(entity,c);
            		c.setCalendarOwner(leaderId);
            		c.setCalendarCategory(cate.get(leaderId));
            		c.setParticipant(partId);
            		c.setViewer(canViewId);
            		c.setMaintainer(maintainId);
            		list.add(c);
            		this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", partId, jsonPart, "oa_calendar", "participant");
            		this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", canViewId, jsonView, "oa_calendar", "viewer");
            		this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainId, jsonMaintain, "oa_calendar", "maintainer");
            	}
        	}

        	this.calendarService.save(list);

        	if(StringUtils.isEmpty(id)) {//新建 可能会是多条
        		boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:leader:01", user.getJwtToken());
    			if(logSet) {
    				for(Calendar calendar : list) {
    					this.logService.saveModuleLog("calendar:leader:01",  calendar.getTitle(), "");
    				}
            	}
        	}else {//修改  修改的时候只能是一条，所以直接使用上面查到的旧名字
        		boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:leader:02", user.getJwtToken());
    			if(logSet) {
            		this.logService.saveModuleLog("calendar:leader:02",  entity.getTitle(), "");
            	}
        	}

        }else {
        	String part = StringUtils.null2String(entity.getParticipant());
        	String entityId = StringUtils.null2String(entity.getId());//为空修改的是重复日程

        	if("".equals(part) || ("".equals(entityId) && !"".equals(type))){
        		part = UuidUtils.UUID();
        		entity.setParticipant(part);
        	}
        	this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", part, jsonPart, "oa_calendar", "participant");

        	String viewer = StringUtils.null2String(entity.getViewer());
        	if("".equals(viewer) || ("".equals(entityId) && !"".equals(type))){
        		viewer = UuidUtils.UUID();
        		entity.setViewer(viewer);
        	}
        	this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", viewer, jsonView, "oa_calendar", "viewer");

        	String maintainer = StringUtils.null2String(entity.getMaintainer());
        	if("".equals(maintainer) || ("".equals(entityId) && !"".equals(type))){
        		maintainer = UuidUtils.UUID();
        		entity.setMaintainer(maintainer);
        	}
        	this.popUserScopeUtilService.saveScopeData("oa_calendar_scope", maintainer, jsonMaintain, "oa_calendar", "maintainer");

        	operationResult = super.editSave(entity);

    		//我的日程、共享日程编辑、新建
    		if(StringUtils.isEmpty(id)) {//新建
    			if("1".equals(isShared)) {//共享日程
    				boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:shareMe:01", user.getJwtToken());
        			if(logSet) {
                		this.logService.saveModuleLog("calendar:shareMe:01",  entity.getTitle(), "");
                	}
    			}else {
    				boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:mycalendar:01", user.getJwtToken());
        			if(logSet) {
                		this.logService.saveModuleLog("calendar:mycalendar:01",  entity.getTitle(), "");
                	}
    			}

    		}else {//编辑
    			if("1".equals(isShared)) {
    				boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:shareMe:02", user.getJwtToken());
        			if(logSet) {
                		this.logService.saveModuleLog("calendar:shareMe:02",  oldCalendarTitle, "");
                	}
    			}else {
    				boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:mycalendar:02", user.getJwtToken());
        			if(logSet) {
                		this.logService.saveModuleLog("calendar:mycalendar:02",  oldCalendarTitle, "");
                	}
    			}
    		}

        	//删除所有子日程编辑的信息
    		calendarService.deleteByBelong(entity.getId());
    		//删除  重复日程删除的日程信息
    		calendarDeleteService.deleteByBelong(entity.getId());
        }
    	Map resultMap = new HashMap();
    	resultMap.put("newCalendarCateId", newCalendarCateId);
    	resultMap.put("oldCalendarCateId", oldCalendarCateId);
    	resultMap.put("isChangeCateId", isChangeCateId);

    	/******************添加推送消息 start************************/
		//门户部件刷新
		List userList = new ArrayList();
		WebsocketUtils.sendMessageByIds(userList,WebsocketConstant.MSGUMC,WebsocketConstant.UMC,WebsocketConstant.MSGPOP,WebsocketConstant.CALENDAR);
		this.calendarService.editOrAddSendMessage(jsonPart,entity,request,userId,corpId,token,allDay);

		/******************添加推送消息 end***********************/

		/**********************推送到evoPortal开始****************/
		//获取日程设置
        Map<String,String> calendarSyncMap = calendarSettingService.getCalendarSettingValue(corpId,"calendarSync");
        String calendarSync = StringUtils.null2String(calendarSyncMap.get("calendarSync"));

        //重复日程不同步
        if( calendarSync.contains("evoPortal") && "no".equals(entity.getDuplicateType())){
        	try {
				this.calendarService.calendarSaveOrUpdateToEvoPortal(entity,corpId,token);
			}catch (Exception e){
        		LOG.error("同步失败",e);
			}
        }
        /**********************推送到evoPortal结束****************/

		String syncModule = StringUtils.null2String(request.getParameter("syncModule"));
    	return OperationResult.buildSuccessResult(StringUtils.isNotBlank(syncModule) ?"同步成功":"保存成功", resultMap);
    }

    /**
     * 在日历视图拖拽日程修改时间
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/updateCalendarDate", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult updateCalendarDate(HttpServletRequest request) {
    	String id = request.getParameter("id");
    	String start = StringUtils.null2String(request.getParameter("start"));
    	String end = StringUtils.null2String(request.getParameter("end"));
    	String allDay = StringUtils.null2String(request.getParameter("allDay"));
    	Calendar calendar = this.calendarService.findOne(id);
    	if("1".equals(calendar.getIsAllDay()) && "false".equals(allDay)){
			return OperationResult.buildFailureResult("全天日程不可拖拽为非全天日程");
		}
    	WebUser user = WebUtils.getCurrentUser();
    	if(StringUtils.isNotBlank(end)){
			calendar.setIsAllDay("0");
		}else{
			calendar.setIsAllDay("1");
		}
    	if(calendar != null){
    		Date startDate = new Date(),endDate = new Date();
    		try {
    			startDate = CalendarUtils.getDataByStr(start, "yyyy-MM-dd");
    			calendar.setStartDate(startDate);
    			if(!"1".equals(calendar.getIsAllDay())){
    				endDate = CalendarUtils.getDataByStr(end, "yyyy-MM-dd");
    				calendar.setEndDate(endDate);
    				int startTime = CalendarUtils.getSecondsByStrDate(start);
    				calendar.setStartTime(startTime);
    				if(!"".equals(end)){
    					int endTime = CalendarUtils.getSecondsByStrDate(end);
        				calendar.setEndTime(endTime);
    				}
    			}
    		} catch (Exception e) {
    			LOG.error("修改时间失败",e);
    		}
    		if(!"no".equals(calendar.getDuplicateType())){
    			this.calendarService.deleteByBelong(id);
    		}
    		logService.saveModuleLog("calendar:mycalendar:02", calendar.getTitle(), "");
    		super.editSave(calendar);
			/**********************推送到evoPortal开始****************/
			//获取日程设置
			Map<String,String> calendarSyncMap = calendarSettingService.getCalendarSettingValue(user.getCorpId(),"calendarSync");
			String calendarSync = StringUtils.null2String(calendarSyncMap.get("calendarSync"));
			//重复日程不同步
			if( calendarSync.contains("evoPortal") && "no".equals(calendar.getDuplicateType())){
				try {
					this.calendarService.calendarSaveOrUpdateToEvoPortal(calendar,user.getCorpId(),user.getJwtToken());
				}catch (Exception e){
					LOG.error("同步日程失败",e);
				}
			}
			/**********************推送到evoPortal结束****************/
			return OperationResult.buildSuccessResult("保存成功");
		}else{
			return OperationResult.buildFailureResult("该日程不可拖拽");
		}
    }

    /**
     * 删除（批量）日程数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
	@WebsocketCode({WebsocketConstant.CALENDAR})
    public OperationResult delete(@RequestParam("id") String id,HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
		//校验id
		if (!ValidateUtils.validateId(id)) {
			throw new ValidationException("非法参数");
		}
    	String classfiyName = StringUtils.null2String(request.getParameter("classfiyName"));
    	String secdatacode =  request.getParameter("secdatacode");
    	if(StringUtils.equals("会议", classfiyName)) {
    		Map<String, String> paramMap = new HashMap<String, String>();
    		//删除会议
    		paramMap.put("id", id);
    		CalendarFinished cf = new CalendarFinished();
    		cf.setCalendarId(id);
    		cf.setPartId(user.getUserId());
    		cf.setCorpId("0");
    		calendarFinishedService.save(cf);
        	return OperationResult.buildSuccessResult("删除成功");
    	}

    	Calendar calendar = this.calendarService.findOne(id);

		List participantUserList = cmpApplyScopeService.getAllUserIdByScope("oa_calendar_scope",
				"oa_calendar", "participant", calendar.getParticipant()
		);
		List viewUserList = cmpApplyScopeService.getAllUserIdByScope("oa_calendar_scope",
				"oa_calendar", "viewer", calendar.getViewer()
		);
		List maintainUserList = cmpApplyScopeService.getAllUserIdByScope("oa_calendar_scope",
				"oa_calendar", "maintainer", calendar.getMaintainer()
		);
		/*if(participantUserList != null && participantUserList.size() > 0){
			allUserList.addAll(participantUserList);
		}
		if(viewUserList != null && viewUserList.size() > 0){
			allUserList.addAll(viewUserList);
		}
		if(maintainUserList != null && maintainUserList.size() > 0){
			allUserList.addAll(maintainUserList);
		}*/
    	if(calendar == null) {
    		return OperationResult.buildFailureResult("该日程已删除");
    	}else{
    		if(calendar.getId()!=null){
                //平行越权校验
                Map<String,String> extMap = new HashMap<>();
                extMap.put("userId",user.getUserId());
                if(!CalendarSecUtils.calendarCheckDataByIdUserId(calendar.getId(),secdatacode,extMap)){
                    return OperationResult.buildFailureResult("操作失败，参数有误");
                }
			}
		}
    	String logLeader = StringUtils.null2String(request.getParameter("logLeader"));
    	//将业务id放到List中
    	List<String> ids = new ArrayList<>();
    	ids.add(id);
    	String type = StringUtils.null2String(request.getParameter("deleteType"));
    	Date start = new Date();
    	OperationResult result = null;
    	//current-删除当前日程，after-删除当前及以后日程，all-删除所有日程，""-删除普通日程或主日程
    	if("all".equals(type) || "".equals(type)){
    		this.calendarDeleteService.deleteByBelong(id);//删除日程删除表标记
    		this.calendarService.deleteByBelong(id);//删除日程
    	}else{
        	CalendarDelete delete  = new CalendarDelete();
        	String eventDate = request.getParameter("eventDate");
			try {
				start = CalendarUtils.getDataByStr(eventDate, "yyyy-MM-dd");
			} catch (Exception e) {
				LOG.error("时间转换失败",e);
			}
        	delete.setDeleteDate(start);
        	if("0".equals(calendar.getIsMain())){
        		delete.setBelongCalendar(calendar.getBelongCalendar());
        	}else{
        		delete.setBelongCalendar(id);
        	}
        	if("current".equals(type) || "after".equals(type)){
        		delete.setDeleteType(type);
        		this.calendarDeleteService.save(delete);
        		if("after".equals(type)){
            		this.calendarService.deleteAfter(id, start);
            	}
        	}
    	}
		if("all".equals(type) || "".equals(type) || "0".equals(calendar.getIsMain())){
    		this.popUserScopeUtilService.delScopeMethod("oa_calendar_scope", StringUtils.null2String(calendar.getParticipant()), "oa_calendar", "participant");
    		this.popUserScopeUtilService.delScopeMethod("oa_calendar_scope", StringUtils.null2String(calendar.getViewer()), "oa_calendar","viewer");
    		this.popUserScopeUtilService.delScopeMethod("oa_calendar_scope", StringUtils.null2String(calendar.getMaintainer()), "oa_calendar","maintainer");
    		result = super.delete(id);
    		calendarSendMsgUtils.deleteMessage(ids,user.getCorpId(),user.getJwtToken());
    	}else{
    		result = OperationResult.buildSuccessResult("删除成功");
    	}
    	String viewType = request.getParameter("viewType");
    	if(StringUtils.isNoneBlank(logLeader)) {
			logService.saveModuleLog("calendar:leader:04", calendar.getTitle(), "");
		}else {
			if(StringUtils.equals(viewType, "share")){
                logService.saveModuleLog("calendar:shareMe:04", calendar.getTitle(), "");
            } else{
                logService.saveModuleLog("calendar:mycalendar:04", calendar.getTitle(), "");
            }
		}

    	/****同步删除evoportal日程开始****/
        Map<String,String> calendarSyncMap = calendarSettingService.getCalendarSettingValue(user.getCorpId(),"calendarSync");
        String calendarSync = StringUtils.null2String(calendarSyncMap.get("calendarSync"));
        //重复日程不同步
        if(calendarSync.contains("evoPortal") && "no".equals(calendar.getDuplicateType())){
        	try {
				this.calendarService.calendarDeleteToEvoPortal(calendar,user.getCorpId());
			}catch (Exception e){
        		LOG.error("同步删除日程失败",e);
			}
        }
        /****同步删除evoportal日程结束****/

		//allUserList.add(calendar.getCreatedBy());
		//websocket刷新时候的通知人
		List allUserList = new ArrayList();
		WebsocketUtils.sendMessageByIds(allUserList,WebsocketConstant.MSGUMC,WebsocketConstant.UMC,WebsocketConstant.MSGPOP,WebsocketConstant.CALENDAR);
        return result;
    }

    /**
	 * 获取用户角色code
	 * @param request
	 * @return  true管理员    false不是管理员
	 */
	@GetMapping("/getUserCode")
	@ResponseBody
    public OperationResult getUserCode(HttpServletRequest request){
		WebUser user = WebUtils.getCurrentUser();
		List<Map<String, Object>> roleList = roleApiService.getRolesByUserId(
				user.getUserId(), user.getCorpId(), user.getJwtToken());
		boolean result = false;
		if (AuthUtils.isSuperAdmin(user)) {
			result = true;
			return OperationResult.buildSuccessResult(result);
		}
		if (!roleList.isEmpty()) {
			String roleCode = "";
			for (Map<String, Object> map : roleList) {
				roleCode = StringUtils.null2String(map.get("roleCode"));
				if("appAdminRole".equals(roleCode)){
					result = true;
					break;
				}
			}
		}
		return OperationResult.buildSuccessResult(result);
	}


    /**
     * 获取一周领导日程的周数和当周的开始时间，结束时间
     * @param request
     * @return
     */
    @RequestMapping(value = "/getWeekDayLead", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getWeekDayLead(HttpServletRequest request){
    	String type = StringUtils.null2String(request.getParameter("type"));
    	String weekTime = StringUtils.null2String(request.getParameter("weekTime"));

		if(!ValidateUtils.validateSql(type) || !ValidateUtils.validateComm(type)){
			throw new ValidationException("非法参数");
		}

    	int week = 0;
    	Map<String, String> map = new HashMap<>();
    	String[] weeks = new String[2];
    	boolean isSameYear = CalendarUtils.isSameYear(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    	int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
    	//如果本周跨年并且今天还没有跨年，得到的weekNum为1，则年份应该用明年的年份
    	if(!isSameYear) {
    		year ++;
    	}
    	if(StringUtils.isBlank(type)) {
    		int weekNum = CalendarUtils.getWeekNum(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    		week = weekNum;
    		weeks = CalendarUtils.getMonthInTwoDate(year,weekNum);
    		//addDays
    	}else if(StringUtils.equals(type, "1")) {
    		week = Integer.valueOf(weekTime).intValue() + 1;
    		weeks = CalendarUtils.getMonthInTwoDate(year,week);
    	}else if(StringUtils.equals(type, "-1")) {
    		week = Integer.valueOf(weekTime).intValue() - 1;
    		weeks = CalendarUtils.getMonthInTwoDate(year,week);
    	}
    	map.put("week", String.valueOf(week));
    	map.put("weekTime", weeks[0].substring(0, 10)+"-"+weeks[1].substring(5, 11));
    	return OperationResult.buildSuccessResult(map);
    }

    /**
     * 新建日程时判断时间段内有无其他日程，0：没有其他日程，1：有其他日程
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/checkCalendarRepeat", method = RequestMethod.GET)
    @ResponseBody
    public String checkCalendarRepeat(HttpServletRequest request) throws ParseException {
    	WebUser user = WebUtils.getCurrentUser();
    	String viewType = StringUtils.null2String(request.getParameter("viewType"));
    	String sharedId = "";
    	String calendarBelong = "";
    	if("share".equals(viewType)){
    		sharedId = StringUtils.null2String(request.getParameter("sharedId"));
    		calendarBelong = StringUtils.null2String(request.getParameter("calendarBelong"));
    	}
    	String title = StringUtils.null2String(request.getParameter("title"));
    	String category = StringUtils.null2String(request.getParameter("category"));
    	String start = request.getParameter("start");
        String isLeader = request.getParameter("isLeader");
		//安全校验
		if(!ValidateUtils.validateSql(start) || !ValidateUtils.validateComm(start)){
			throw new ValidationException("非法参数");
		}

    	String end = request.getParameter("end");
    	String stm = request.getParameter("stm");
    	String etm = request.getParameter("etm");
		String leader = request.getParameter("leader");
		String isAllDay = request.getParameter("isAllDay");
		//安全校验
		if(!ValidateUtils.validateSql(isAllDay) || !ValidateUtils.validateComm(isAllDay)){
			throw new ValidationException("非法参数");
		}

		String leaderOrSubId = request.getParameter("leaderOrSubId");
		String mainId = request.getParameter("mainId");
		if("1".equals(isAllDay)) {
			stm = "00:00";
			etm = "23:59";
			end = start;
		}

		String flag = "0";


		String result;
        //如果是领导日程complateCalendar
        if (StringUtils.isNotBlank(leader)) {
            if("1".equals(isLeader)){
                result = this.calendarService.getOaCalendarForLeader("", sharedId, user.getCorpId(), title, category,"calendar", start, end, TOKEN,leader,user);
            }else{
                result = this.calendarService.getOaCalendar("", sharedId, user.getCorpId(), title, category,"calendar", start, end, TOKEN,leader,user);
            }
        }else{
            result = this.calendarService.getOaCalendar(sharedId, user.getUserId(), user.getCorpId(), title, category,viewType, start, end, TOKEN,leader,user);
        }


    	if(!"[]".equals(result)) {
    		JSONArray json = JSONArray.parseArray(result);
//    		LOG.error("共享给我的日程:"+json.toJSONString());
    		for (int i = 0; i < json.size(); i++) {
				JSONObject job = json.getJSONObject(i);
				String id = job.get("mainId")+"";
				if(id.equals(mainId)) {
					continue;
				}
				String startTime = job.get("start")+"";
				String endTime = job.get("end")+"";
				String stm2;
				String etm2;
				if(startTime.indexOf("T")<0 && "null".equals(endTime)) {
					startTime = startTime +"T";
					endTime = startTime;
					stm2 = "00:00";
					etm2 = "23:59";
				}else {
					stm2 = startTime.substring(startTime.indexOf("T")+1,startTime.length());
					etm2 = endTime.substring(endTime.indexOf("T")+1,endTime.length());
				}
				String start2 = startTime.substring(0,startTime.indexOf("T"));
				String end2 = endTime.substring(0,endTime.indexOf("T"));
				String duplicateType = job.get("isDuplicate")+"";
				if(!"no".equals(duplicateType)) {
					if(DateUtils.parseDate(start).after(DateUtils.parseDate(end2))){
						continue;
					} else if(DateUtils.parseDate(end).before(DateUtils.parseDate(start2))){
						continue;
					}

				}
				if(!start.equals(end) && !start2.equals(end2)) {
					if(end2.equals(start)) {
						if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
							flag = "0";
						}else {
							flag = "1";
							break;
						}
					}else if(end.equals(start2)) {
						if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
							flag = "0";
						}else {
							flag = "1";
							break;
						}
					}else {
						flag = "1";
						break;
					}
				}else if(!start.equals(end) && start2.equals(end2)) {
					if(start.equals(end2)) {
						if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
							flag = "0";
						}else {
							flag = "1";
							break;
						}
					}else if(end.equals(start2)) {
						if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
							flag = "0";
						}else {
							flag = "1";
							break;
						}
					}else {
						flag = "1";
						break;
					}
				}else if(start.equals(end) && !start2.equals(end2)) {
					if(end2.equals(start)) {
						if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
							flag = "0";
						}else {
							flag = "1";
							break;
						}
					}else if(start2.equals(start)) {
						if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
							flag = "0";
						}else {
							flag = "1";
							break;
						}
					}else {
						flag = "1";
						break;
					}
				}else if(start.equals(end) && start2.equals(end2) && start.equals(start2)){
					if(CalendarUtils.getSeconds(etm2)<=CalendarUtils.getSeconds(stm)) {
						flag = "0";
					}else if(CalendarUtils.getSeconds(stm2)>=CalendarUtils.getSeconds(etm)) {
						flag = "0";
					}else {
						flag = "1";
						break;
					}
				}else {
					flag = "0";
				}
			}
    	}
    	return flag;
    }

    /**
     * 概览模式导出
     * @param request
     */
    @RequestMapping(value = "/exportCalendar", method = RequestMethod.POST)
    @ResponseBody
    public String exportCalendar(HttpServletRequest request,  HttpServletResponse response) {
    	WebUser user = WebUtils.getCurrentUser();
    	String viewType = request.getParameter("viewType");
    	String weekTime = request.getParameter("weekTime");
    	String exportName = request.getParameter("exportName");
    	String cateSelect = request.getParameter("cateSelect");

		if(!ValidateUtils.validateSql(viewType)){
			throw new ValidationException("非法参数");
		}
		if(!ValidateUtils.validateParam(viewType)){
			throw new ValidationException("非法参数");
		}
		if(weekTime!=null && !ValidateUtils.validateInt(weekTime)){
			throw new ValidationException("非法参数");
		}
		if(!ValidateUtils.validateSql(exportName)){
			throw new ValidationException("非法参数");
		}

//		if(!ValidateUtils.validateParam(exportName)){
//			throw new ValidationException("非法参数");
//		}

		if(!ValidateUtils.validateSql(cateSelect) || !ValidateUtils.validateComm(cateSelect)){
			throw new ValidationException("非法参数");
		}

    	boolean isSameYear = CalendarUtils.isSameYear(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    	int year = Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date())).intValue();
    	//如果本周跨年并且今天还没有跨年，得到的weekNum为1，则年份应该用明年的年份
    	if(!isSameYear) {
    		year ++;
    	}
    	String[] week = CalendarUtils.getMonthInTwoDate(year,Integer.parseInt(weekTime));
		String start = week[0];
		String end = week[1];
		start = start.replace("年", "-").replace("月", "-").replace("日", "");
		end = end.replace("年", "-").replace("月", "-").replace("日", "");
		List<Map<String, String>> list = null;
		if(StringUtils.equals("calendar", viewType)){
            list = calendarService.getOaWeekCalendarList(user.getUserId(), user.getCorpId(), "calendar", start, end, TOKEN, "myCalendar");
        }else{
            list = calendarService.getOaWeekCalendarList(cateSelect, user.getCorpId(), "calendar", start, end, TOKEN, "leaderCalendar");

			//对数据进行处理，参与日程替换成相关领导
			for(Map<String, String> calendarMap : list){
				//参与日程
				if("参与日程".equals(calendarMap.get("category"))){
					List<Map<String,Object>> userMapList = userApiService.getUserList(cateSelect, user.getCorpId(), "", user.getJwtToken());
					Map<String,Map<String,Object>> userIdForKeyMap = new HashMap<>();
					for(Map<String,Object> userMap : userMapList){
						userIdForKeyMap.put(userMap.get("id").toString(),userMap);
					}
					List<String> scopeValueList = calendarDao.selectScopeValueList(calendarMap.get("participant2"));
					String leaderNames = "";
					for(String scopeValue : scopeValueList){
						if(userIdForKeyMap.get(scopeValue)!=null){
							leaderNames = leaderNames+","+userIdForKeyMap.get(scopeValue).get("userName");
						}
					}
					if(leaderNames.length()>0){
						leaderNames = leaderNames.substring(1);
					}


					calendarMap.put("owner",leaderNames);
				}
			}
        }
		Map<String, List<Map<String, String>>> allMap = new LinkedHashMap<String, List<Map<String, String>>>();
		String temp = "";
		List<Map<String, String>> tempList = null;
		for (Map<String, String> map : list) {
			if(temp.equals(map.get("weekNumber"))) {
				tempList.add(map);
			}else {
				tempList = new ArrayList<Map<String, String>>();
				temp = map.get("weekNumber");
				tempList.add(map);
				allMap.put(temp, tempList);
			}
		}
		Map<String, Integer> map = new LinkedHashMap<String, Integer>();
		for(Map.Entry<String, List<Map<String, String>>> entry : allMap.entrySet()) {
			int num = entry.getValue().size();
			map.put(entry.getKey(), num);
		}
		String fileName = exportName+".xls";
		//记录日志
		if(CollectionUtils.isNotEmpty(list)) {//有数据就记录
			if(StringUtils.equals(viewType, "calendar")) {
				boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:mycalendar:05", user.getJwtToken());
				if(logSet) {
					this.logService.saveModuleLog("calendar:mycalendar:05", exportName,"");
				}

			}else {
				boolean logSet = this.logService.checkOptLog(user.getCorpId(), "calendar:leader:05", user.getJwtToken());
				if(logSet) {
					this.logService.saveModuleLog("calendar:leader:05", exportName ,"");
				}

			}
		}
		OutputStream out = null;
		InputStream in = null;
		try {
			calendarExportUtil.createXls(list, fileName, map, viewType);
			responseContentDisposition(fileName, request, response);
			out = response.getOutputStream();
	        in = new FileInputStream(fileName);
	        //写文件
		    int b;
		    while((b=in.read())!= -1)
		    {
		        out.write(b);
		    }
		        in.close();
				out.flush();
				out.close();
		} catch (IOException e) {
			LOG.error("导出失败",e);
		}finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LOG.error("输入流关闭失败",e);
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LOG.error("输出流关闭失败",e);
				}
			}
		}
		return null;
    }

    /**
     *
     * @param fileName
     * @param request
     * @param response
     */
    private void responseContentDisposition(String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            String finalFileName = null;
            finalFileName = AttachUtils.encodingFileName(fileName, request);
        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") != -1){
                response.addHeader("Content-Disposition", "attachment;filename*=UTF-8''" + finalFileName);
        }else {
                response.setHeader("Content-Disposition", "attachment; filename=" + finalFileName);
        }
            response.setContentType("APPLICATION/OCTET-STREAM");
        } catch (Exception e) {
        	LOG.error("导出失败",e);
        }
    }

    /**
     * 会议同步至日程
     * @param request
     * @return
     */
    @RequestMapping(value = "/editSaveMeeting", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult editSaveMeeting(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("owner", request.getParameter("owner"));//日程拥有人id
    	map.put("title", request.getParameter("title"));//标题
    	map.put("startTime", request.getParameter("startTime"));//开始时间
    	map.put("endTime", request.getParameter("endTime"));//结束时间
    	map.put("content", request.getParameter("content"));//内容
    	map.put("address", request.getParameter("address"));//地址
    	map.put("attId", request.getParameter("attId"));//附件id
    	map.put("meetingId", request.getParameter("meetingId"));//会议数据id
    	map.put("meetingFormId", request.getParameter("meetingFormId"));//会议表单id
    	map.put("calendarId", request.getParameter("calendarId"));//日程id
    	Calendar calendar = calendarService.editSaveMeeting(map,user);
    	return OperationResult.buildSuccessResult("同步成功",calendar.getId());
    }

    /*
	 * 判断日程是否有参与人
	 *
	 */
	@RequestMapping(value = "/checkHasPart", method = RequestMethod.GET)
	@ResponseBody
    public OperationResult checkHasPart(HttpServletRequest request){

		String suffix = request.getParameter("_");
		if(!ValidateUtils.validateSql(suffix) || !ValidateUtils.validateComm(suffix) ){
			throw new ValidationException("非法参数");
		}

		String calendarId = request.getParameter("calendarId");//日程id
		boolean hasPart = false;
		if(StringUtils.isNotBlank(calendarId)){
			hasPart = calendarService.calendarHasPart(calendarId);
		}

		Map<String,Object> resultMap = new HashMap<>();
		resultMap.put("hasPart",hasPart);
		return OperationResult.buildSuccessResult(resultMap);
	}

	/*
	 * 判断给定用户是否完成给定日程
	 *
	 */
	@RequestMapping(value = "/checkComplete", method = RequestMethod.GET)
	@ResponseBody
	public OperationResult checkComplete(HttpServletRequest request){
		String calendarId = request.getParameter("calendarId");//日程id
		String userId = request.getParameter("userId");//用户id

		boolean isComplete = calendarService.checkComplete(calendarId,userId);

		Map<String,Object> resultMap = new HashMap<>();
		resultMap.put("isComplete",isComplete);
		return OperationResult.buildSuccessResult(resultMap);
	}

	/**
	 * 判断给定的日程是否存在
	 *
	 */
	@RequestMapping(value = "/checkExist", method = RequestMethod.GET)
	@ResponseBody
	public OperationResult checkExist(HttpServletRequest request){
		String calendarId = request.getParameter("calendarId");//日程id
		Calendar calendar = this.calendarService.findOne(calendarId);
        WebUser user = WebUtils.getCurrentUser();
		boolean isExist = true;
		String secdatacode = "";
		if(calendar == null || calendar.getId()==null){
			isExist = false;
		}else{
		    //获取加密信息
            Map map = new HashMap();
            map.put("id",calendar.getId());
            map.put("userId",user.getUserId());
            Map encodeMap =  DealFieldEncodeUtils.dealDataMap(map,"id,userId","calendar",null);
            secdatacode = encodeMap.get("secdatacode").toString();
        }


		Map<String,Object> resultMap = new HashMap<>();
		resultMap.put("isExist",isExist);
        resultMap.put("secdatacode",secdatacode);
		return OperationResult.buildSuccessResult(resultMap);
	}

	/**
	 * 详情模式导出
	 * @param request
	 */
	@RequestMapping(value = "/normalExportCalendar", method = RequestMethod.POST)
	@ResponseBody
	public String normalExportCalendar(HttpServletRequest request,  HttpServletResponse response) {
		WebUser user = WebUtils.getCurrentUser();

		String userId = request.getParameter("userId");
		String cateId = request.getParameter("cateId");
		String startTime = request.getParameter("startTime");
		String endTime =  request.getParameter("endTime");
		String viewType = request.getParameter("viewType");
		String leaderOrSub = request.getParameter("leaderOrSub");
		String calendarCate = request.getParameter("calendarCate");
		String leaderOrSubName = request.getParameter("leaderOrSubName");
		String selectViewType = request.getParameter("selectViewType");
		String customId = request.getParameter("customId");

		String exportName = request.getParameter("exportName");

		Map<String, String> paramMaps = new HashMap<>();
		paramMaps.put("userId",userId);
		paramMaps.put("cateId",cateId);
		paramMaps.put("startTime",startTime);
		paramMaps.put("endTime",endTime);
		paramMaps.put("viewType",viewType);
		paramMaps.put("leaderOrSub",leaderOrSub);
		paramMaps.put("calendarCate",calendarCate);
		paramMaps.put("leaderOrSubName",leaderOrSubName);
		paramMaps.put("selectViewType",selectViewType);
		paramMaps.put("customId",customId);

		List<Calendar> exportList = calendarService.getDemoExport(paramMaps);

		OutputStream out = null;
		InputStream in = null;
		String fileName = exportName+".xls";
		try {
			calendarExportUtil.createNormalXls(exportList, fileName, selectViewType);
			responseContentDisposition(fileName, request, response);
			out = response.getOutputStream();
			in = new FileInputStream(fileName);
			//写文件
			int b;
			while((b=in.read())!= -1)
			{
				out.write(b);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			LOG.error("导出失败",e);
		}finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LOG.error("输入流关闭失败",e);
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LOG.error("输出流关闭失败",e);
				}
			}
		}
		return null;
	}



}
